package com.qidian.buy.cms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qidian.buy.cms.mapper.ContentCategoryMapper;
import com.qidian.buy.common.exceptions.ServiceException;
import com.qidian.buy.common.pojo.BuyPager;
import com.qidian.buy.common.pojo.BuyResult;
import com.qidian.buy.common.util.JSONTools;
import com.qidian.buy.common.util.ThreadPoolUtil;
import com.qidian.buy.pojo.Content;
import com.qidian.buy.cms.mapper.ContentMapper;
import com.qidian.buy.cms.service.IContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.pojo.ContentCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2024-07-12 10:23:40
 */
@Service
public class ContentServiceImpl  implements IContentService {

    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private ContentCategoryMapper categoryMapper;
    // 绑定缓存key的前缀
    @Value("${content-pre:}")
    private String contentPre;
    @Value("${thread-pool-name}")
    private String threadPoolName;
    // 注入redis的工具类
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public BuyResult queryByCatMark(String catMark) {
        // 准备key
        String key = contentPre + catMark; // CONTENT_INDEX_LUNBO
        // 查询reids中是否有数据
        if(redisTemplate.hasKey(key)){
            String json = redisTemplate.opsForValue().get(key);
            // 将JSON转换为列表
            try {
                // 有就直接返回
                List<Content> contents = JSONTools.json2list(json, Content.class);
                // 这里直接返回即可
                return BuyResult.success(contents);
            } catch (Exception e) {
                // 记录日志
                // 转换失败，记录日志之后，将这个key删除
                redisTemplate.delete(key);
            }
        }
        // 没有数据就从数据库查询
        List<Content> contents = contentMapper.selectByCatMark(catMark);
        if(contents != null && contents.size() > 0) {
            // 将从数据库查询的数据给redis存储一份
            redisTemplate.opsForValue().set(key,JSONTools.object2json(contents));
            // 设置一个缓存的时间,缓存的有效期
            redisTemplate.expire(key,30, TimeUnit.MINUTES);
        }
        return BuyResult.success(contents);
    }

    @Override
    public BuyResult queryPage(int pageNum, int limit, Content content) {
        // 查询数据列表
        List<Content> contents = contentMapper.selectPage((pageNum - 1) * limit ,limit,content);
        // 查询总条数
        int total = contentMapper.selectTotal(content);
        return BuyResult.success(new BuyPager<Content>(pageNum,limit,total,contents));
    }

    @Override
    public BuyResult saveContent(Content content) {
        ContentCategory category = categoryMapper.selectById(content.getCatId());
        String key = contentPre + category.getCatMark();
        // 先删除缓存
        redisTemplate.delete(key);
        // 保存数据
        int result = contentMapper.insert(content);
        // 开启子线程等一会再次删除缓存
        // 获取线程池对象
        ExecutorService pool = ThreadPoolUtil.getPool(threadPoolName);
        pool.submit(()->{
            int count = 0;
            while(count < 10){
                try {
                    //等到100毫秒再次删除
                    TimeUnit.MILLISECONDS.sleep(100);
                    if(redisTemplate.delete(key)){// 删除失败就重试
                        break;
                    }
                    count ++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            if(count == 10){
                // 重试10次都失败了
                // 记录异常
                throw new ServiceException("清空缓存" + key + "失败");
            }
        });
        return BuyResult.isSuccess(result);
    }


}
